<template>
  <div>
    <box t1="权限管理" t2="角色列表">
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border="" stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <!-- 角色下权限的树状结构 -->
          <!-- scope.row 就是角色对象 -->
          <!-- scope.row.children 就是该角色下的一级权限 -->
          <template slot-scope="scope">
            <!-- 每一个一级权限独立显示一行 -->
            <el-row
              :class="[ 'bdbottom', i1===0?'bdtop':'','vcenter']"
              v-for="(item,i1) in scope.row.children"
              :key="item.id"
            >
              <!-- 一级权限菜单的显示列 -->
              <el-col :span="5">
                <el-tag closable @close="deleteRights(scope.row,item.id)">{{ item.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 包裹2级与3级权限的显示列 -->
              <el-col :span="19">
                <!-- 每一个二级权限都是在这个列中独立的一行 -->
                <el-row
                  :class="[ i2 === 0?'':'bdtop','vcenter']"
                  v-for="(item2,i2) in item.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      closable
                      @close="deleteRights(scope.row,item2.id)"
                      type="success"
                    >{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      closable
                      @close="deleteRights(scope.row,item3.id)"
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                    >{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
            <el-button
              size="mini"
              type="warning"
              @click="showRightsBox(scope.row)"
              icon="el-icon-setting"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </box>
    <!-- 分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      @close="defaultKeys=[]"
      width="50%"
    >
      <!-- node-key指定每一个节点里的key值是id属性值 -->
      <el-tree
        ref="treeRef"
        :default-checked-keys="defaultKeys"
        default-expand-all
        show-checkbox
        node-key="id"
        :data="rightsList"
        :props="treeProp"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      roleInfo: {},
      setRightDialogVisible: false,
      rightsList: [],
      // tree组件的配置对象
      treeProp: {
        label: "authName",
        children: "children"
      },
      // 默认被选中的权限数组
      defaultKeys: []
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("数据获取失败");
      }

      this.rolesList = res.data;
    },
    async deleteRights(role, rid) {
      // 调用confirm弹窗
      let result = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(error => error);

      if (result != "confirm") {
        return this.$message.info("用户取消删除");
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rid}`
      );
      if (res.meta.status !== 200) {
        return this.$message.error("删除失败");
      }
      // 成功的话 我们就重新赋值角色的children属性
      role.children = res.data;
    },
    async showRightsBox(roleInfo) {
      // 打开分配角色弹窗 保存当前的角色信息
      this.roleInfo = roleInfo;
      this.setRightDialogVisible = true;
      // 打开弹窗要看到所有权限的一个树状的结构
      // 要获取所有的权限列表
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200) {
        return this.$message.error("获取权限列表失败");
      }
      this.rightsList = res.data;
      // 需要把当前角色下所有的权限 默认显示到tree上
      // 只要获得当前角色的所有三级权限的id 放在一个数组中 把数组赋值给tree组件的 一个属性default-checked-keys
      this.getLeafKeys(roleInfo, this.defaultKeys);
    },
    // 通过一个递归函数获取角色下所有的三级权限
    getLeafKeys(node, arr) {
      // 递归的终止条件 三级权限没有children
      if (!node.children) {
        return arr.push(node.id);
      }

      node.children.forEach(item => this.getLeafKeys(item, arr));
    },
    async allotRights() {
      let keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      keys = keys.join(",");
      const { data: res } = await this.$http.post(
        `roles/${this.roleInfo.id}/rights`,
        { rids: keys }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("修改权限失败");
      }
      // 修改成功 则关闭弹窗
      this.setRightDialogVisible = false;
      // 重新加载列表
      this.getRolesList();
    }
  }
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>